package edu.sju.chenshu.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import edu.sju.chenshu.common.core.constants.HttpConstants;
import edu.sju.chenshu.common.core.utils.ThreadLocalUtil;
import edu.sju.chenshu.common.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;

    @Value("${jwt.secret}")
    private String jwtSecret;  //从哪个服务的配置文件中取,取决于bean对象交给了哪个服务的Spring容器进行管理

    //到达目标方法前
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        tokenService.extendToken(token, jwtSecret);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }

    //从请求头中获取token
    public String getToken(HttpServletRequest request){
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.substring(HttpConstants.PREFIX.length());
        }
        return token;
    }
}
